var VSHADER_SOURCE =
    'attribute vec4 a_Position;\n' +
    'attribute vec4 a_Color;\n' + //物体颜色
    'attribute vec4 a_Normal;\n' + //法向量
    'uniform mat4 u_MvpMatrix;\n' + //模型视图投影矩阵
    'uniform mat4 u_ModelMatrix;\n' + // 模型矩阵
    'uniform mat4 u_NormalMatrix;\n' + // 法向量变换矩阵
    'varying vec4 v_Color;\n' +
    'varying vec3 v_Normal;\n' +
    'varying vec3 v_Position;\n' +
    'void main() {\n' +
    '  gl_Position = u_MvpMatrix * a_Position;\n' +
    // 计算世界坐标下的定点坐标
    '  v_Position = vec3(u_ModelMatrix * a_Position);\n' +
    '  v_Normal = normalize(vec3(u_NormalMatrix * a_Normal));\n' +
    '  v_Color = a_Color;\n' +
    '}\n';

// Fragment shader program
var FSHADER_SOURCE =
    '#ifdef GL_ES\n' +
    'precision mediump float;\n' +
    '#endif\n' +
    'uniform vec3 u_LightColor;\n' + // 光照颜色
    'uniform vec3 u_LightPosition;\n' + // 光的位置
    'uniform vec3 u_AmbientLight;\n' + // 环境光的颜色
    'varying vec3 v_Normal;\n' +
    'varying vec3 v_Position;\n' +
    'varying vec4 v_Color;\n' +
    'void main() {\n' +
    // 对法线进行归一化
    '  vec3 normal = normalize(v_Normal);\n' +
    // 计算光线方向并归一化
    '  vec3 lightDirection = normalize(u_LightPosition - v_Position);\n' +
    // 计算光线方向和法向量的点积
    '  float nDotL = max(dot(lightDirection, normal), 0.0);\n' +
    // 计算光照效果和环境光照效果
    '  vec3 diffuse = u_LightColor * v_Color.rgb * nDotL;\n' +
    '  vec3 ambient = u_AmbientLight * v_Color.rgb;\n' +
    //计算最终光照效果
    '  gl_FragColor = vec4(diffuse + ambient, v_Color.a);\n' +
    '}\n';


function main() {

    var canvas = document.getElementById('cylinder');

    var gl = WebGLUtils.setupWebGL(canvas);
    if (!gl) {
        console.log('Failed to get the rendering context for WebGL');
        return;
    }


    gl.clearColor(0.0, 0.0, 0.0, 0.0);
    gl.enable(gl.DEPTH_TEST);
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

    drawBall([1.0, 0.0, 0.0, 1.0], [1, 1, 1], 0.5, 2, [1.0, 0.0, 0.0], gl, [0, 2, 20]);

    // drawBall([1.0, 0.0, 0.0, 1.0], 0.5, 0.5, [1.0, 0.0, 0.0], gl);
}

/**
 * [drawBall 画球]
 * @param  {四元数组} vertice1 球心坐标
 * @param  {三元数组} vector 球的上方向
 * @param  {数值} half    为0.5时为半球,为1时为整球
 * @param  {数值} r       球半径
 * @param  {[三元数组]} colors  球颜色
 * @param  {[type]} gl      [description]
 * @param  {[三元数组]} eye  设置视点
 * @return {[type]}         [description]
 */
function drawBall(vertice, vector, half, r, colors, gl, eye) {

    if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
        console.log('Failed to intialize shaders.');
        return;
    }

    var modelMatrix = new Matrix4();
    var a_zx;
    var a_z;;
    if (vector[0] == 0) {
        a_zx = Math.PI / 2;
        if (vector[2] < 0) {
            a_zx = a_zx * (-1);
        }
    } else {
        if (vector[2] == 0) {
            if (vector[0] > 0) {
                a_zx = 0;
            } else {
                a_zx = Math.PI;
            }

        } else {
            a_zx = Math.atan(vector[2] / vector[0]);
        }
    }

    var x_y_z = Math.sqrt(vector[0] * vector[0] + vector[1] * vector[1] + vector[2] * vector[2]);
    if (vector[1] == 0) {
        a_z = Math.PI / 2;
    } else {
        a_z = Math.acos(vector[1] / x_y_z);
    }

    modelMatrix.setTranslate(vertice[0], vertice[1], vertice[2]);
    modelMatrix.rotate(180 * a_zx / Math.PI, 0, 1, 0);
    modelMatrix.rotate(180 * a_z / Math.PI, 0, 0, 1);
    modelMatrix.rotate((-1) * 180 * a_zx / Math.PI, 0, 1, 0);

    //初始化缓存区
    var n = ballInitVertexBuffers(gl, half, r, colors);
    if (n < 0) {
        console.log('Failed to set the vertex information');
        return;
    }

    var u_ModelMatrix = gl.getUniformLocation(gl.program, 'u_ModelMatrix');
    var u_MvpMatrix = gl.getUniformLocation(gl.program, 'u_MvpMatrix');
    var u_NormalMatrix = gl.getUniformLocation(gl.program, 'u_NormalMatrix');
    var u_LightColor = gl.getUniformLocation(gl.program, 'u_LightColor');
    var u_LightPosition = gl.getUniformLocation(gl.program, 'u_LightPosition');
    var u_AmbientLight = gl.getUniformLocation(gl.program, 'u_AmbientLight');
    if (!u_ModelMatrix || !u_MvpMatrix || !u_NormalMatrix || !u_LightColor || !u_LightPosition || !u_AmbientLight) {
        console.log('Failed to get the storage location');
        return;
    }

    // 设置光照颜色 (white)
    gl.uniform3f(u_LightColor, 1.0, 1.0, 1.0);
    // 光位置 (in the world coordinate)
    gl.uniform3f(u_LightPosition, 2.3, 4.0, 3.5);
    // 环境光
    gl.uniform3f(u_AmbientLight, 0.2, 0.2, 0.2);


    var mvpMatrix = new Matrix4();
    var normalMatrix = new Matrix4();

    mvpMatrix.setPerspective(30, 1, 1, 100);
    mvpMatrix.lookAt(eye[0], eye[1], eye[2], 0, 0, 0, 0, 1, 0);

    mvpMatrix.multiply(modelMatrix);

    normalMatrix.setInverseOf(modelMatrix);
    normalMatrix.transpose();

    gl.uniformMatrix4fv(u_ModelMatrix, false, modelMatrix.elements);

    gl.uniformMatrix4fv(u_MvpMatrix, false, mvpMatrix.elements);

    gl.uniformMatrix4fv(u_NormalMatrix, false, normalMatrix.elements);
    // gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
    gl.drawElements(gl.TRIANGLES, n, gl.UNSIGNED_SHORT, 0);
}

function ballInitVertexBuffers(gl, half, r, color) {

    var SPHERE_DIV = 26;
    var colors = new Float32Array((SPHERE_DIV + 1) * (SPHERE_DIV + 1) * 3);
    var i, ai, si, ci;
    var j, aj, sj, cj;
    var p1, p2;

    var positions = [];
    var indices = [];


    var index = 0;
    // Generate coordinates
    for (j = 0; j <= SPHERE_DIV; j++) {
        aj = j * Math.PI * half / SPHERE_DIV;
        sj = r * Math.sin(aj);
        cj = r * Math.cos(aj);
        for (i = 0; i <= SPHERE_DIV; i++) {
            ai = i * 2 * Math.PI / SPHERE_DIV;
            si = Math.sin(ai);
            ci = Math.cos(ai);

            positions.push(si * sj); // X
            positions.push(cj); // Y
            positions.push(ci * sj); // Z

            colors.set(color, index);
            index += 3;
        }
    }

    // Generate indices
    for (j = 0; j < SPHERE_DIV; j++) {
        for (i = 0; i < SPHERE_DIV; i++) {
            p1 = j * (SPHERE_DIV + 1) + i;
            p2 = p1 + (SPHERE_DIV + 1);

            indices.push(p1);
            indices.push(p2);
            indices.push(p1 + 1);

            indices.push(p1 + 1);
            indices.push(p2);
            indices.push(p2 + 1);
        }
    }


    if (!initArrayBuffer(gl, 'a_Position', new Float32Array(positions), 3)) return -1;
    if (!initArrayBuffer(gl, 'a_Color', colors, 3)) return -1;
    if (!initArrayBuffer(gl, 'a_Normal', new Float32Array(positions), 3)) return -1;


    gl.bindBuffer(gl.ARRAY_BUFFER, null);


    var indexBuffer = gl.createBuffer();
    if (!indexBuffer) {
        console.log('Failed to create the buffer object');
        return false;
    }
    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
    gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);

    return indices.length;
}


function initArrayBuffer(gl, attribute, data, num) {
    // Create a buffer object
    var buffer = gl.createBuffer();
    if (!buffer) {
        console.log('Failed to create the buffer object');
        return false;
    }
    // Write date into the buffer object
    gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
    gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);
    // Assign the buffer object to the attribute variable
    var a_attribute = gl.getAttribLocation(gl.program, attribute);
    if (a_attribute < 0) {
        console.log('Failed to get the storage location of ' + attribute);
        return false;
    }
    gl.vertexAttribPointer(a_attribute, num, gl.FLOAT, false, 0, 0);
    // Enable the assignment of the buffer object to the attribute variable
    gl.enableVertexAttribArray(a_attribute);

    return true;
}